
package taller2.controller.modes;

import java.awt.event.MouseEvent;
import java.util.ArrayList;

import taller2.interfaces.AlgorithmApplicator;
import taller2.interfaces.Graph;
import taller2.interfaces.InitialNodeApplicator;
import taller2.interfaces.Node;
import taller2.utils.Constants.Colores;
import taller2.utils.Point;
import taller2.view.draws.DrawingArea;
import taller2.view.draws.GraphDrawer;

public class BeginNodeMode implements Mode{
	private AlgorithmApplicator algorithmApplicator;
	private Graph graph;
	private Node selected;
	
	// constructor
	public BeginNodeMode(AlgorithmApplicator algorithmApplicator, Graph graph){
		this.algorithmApplicator = algorithmApplicator;
		this.graph = graph;
	}
	
	// when the mouse is pressed the initial node for the algorithm is
	// informed to the applicator
	public void whenPressed(MouseEvent arg0, DrawingArea area) {
		
		boolean encontrado = false;
		Point posObj = new Point(arg0.getX(),arg0.getY());
		GraphDrawer drawer = area.getDrawer();
		
		ArrayList<Node> nodes = graph.getNodes();
		for(Node node : nodes){
			Colores color = node.getColor();
			if(color == Colores.purple || color == Colores.red)
				node.changeColor(Colores.yellow);
			
			if(drawer.isCloseEnough(node, posObj)){
			//si esta lo suficientemente cerca...	
				selected = node;
				selected.changeColor(Colores.purple);
				encontrado = true;
				
				nodes = graph.getNodes();
				for(int i=0 ; i < nodes.size() ; i++){
					Node n = nodes.get(i);
					if(n.equals(selected)){
						//Atencion: debe implementar InitialNodeApplicator!!
						((InitialNodeApplicator) algorithmApplicator).setInitialNode(i);		
					}
				}							
			}
		}
		
		if (encontrado == false){
			selected = graph.getFirstNode();
			
			//Atencion: debe implementar InitialNodeApplicator!!
			((InitialNodeApplicator) algorithmApplicator).setInitialNode(0);
		}
		
		area.repaint();	
	}

	public void whenReleased(MouseEvent arg0, DrawingArea area) {}

	public void whenDragged(MouseEvent arg0, DrawingArea area) {}

}